<template>
  <div class="permission-list-tab">
    <!-- 搜索和操作栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="filterForm" class="filter-form" @submit.prevent>
        <el-form-item label="权限名称">
          <el-input 
            v-model="filterForm.name" 
            placeholder="请输入权限名称" 
            clearable 
            style="width: 200px"
            @input="handleSearchInput"
          />
        </el-form-item>
        <el-form-item label="权限类型">
          <el-select v-model="filterForm.type" placeholder="请选择权限类型" clearable style="width: 150px" @change="handleSearch">
            <el-option 
              v-for="option in PERMISSION_TYPE_OPTIONS" 
              :key="option.value" 
              :label="option.label" 
              :value="option.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.enable" placeholder="请选择状态" clearable style="width: 120px" @change="handleSearch">
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 权限表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>权限列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAddPermission">
              <el-icon><Plus /></el-icon> 新增权限
            </el-button>
            <el-button type="success" @click="handleBatchAdd">
              <el-icon><Upload /></el-icon> 批量导入
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="permissionList"
        style="width: 100%"
        border
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="id" label="ID" width="60" sortable />
        <el-table-column prop="name" label="权限名称" min-width="150" />
        <el-table-column prop="code" label="权限代码" min-width="150" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路径" min-width="200" show-overflow-tooltip />
        <el-table-column prop="icon" label="图标" width="80">
          <template #default="{ row }">
            <el-icon v-if="row.icon" :size="16">
              <component :is="row.icon" />
            </el-icon>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="method" label="方法" width="80">
          <template #default="{ row }">
            <el-tag v-if="row.method" :type="getMethodTagType(row.method)" size="small">
              {{ row.method }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="order" label="排序" width="80" sortable />
        <el-table-column prop="show" label="显示" width="80">
          <template #default="{ row }">
            <el-tag :type="row.show ? 'success' : 'info'" size="small">
              {{ row.show ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enable" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.enable ? 'success' : 'danger'" size="small">
              {{ row.enable ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
              :disabled="row.roles && row.roles.length > 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 权限编辑对话框 -->
    <PermissionEditDialog 
      v-model="dialogVisible"
      :permission="currentPermission"
      :is-edit="isEdit"
      @success="handleDialogSuccess"
    />

    <!-- 批量导入对话框 -->
    <PermissionBatchDialog 
      v-model="batchDialogVisible"
      @success="handleBatchSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { 
  Search, 
  Refresh, 
  Plus,
  Upload
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { permissionApi, Permission, PermissionQueryParams, PERMISSION_TYPE_OPTIONS } from '../api/permission'
import PermissionEditDialog from './PermissionEditDialog.vue'
import PermissionBatchDialog from './PermissionBatchDialog.vue'
import { debounce } from '../utils/common'

// 加载状态
const loading = ref(false)

// 分页配置
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)

// 权限列表
const permissionList = ref<Permission[]>([])

// 过滤表单
const filterForm = reactive<PermissionQueryParams>({
  name: '',
  type: undefined,
  enable: undefined
})

// 对话框相关
const dialogVisible = ref(false)
const batchDialogVisible = ref(false)
const isEdit = ref(false)
const currentPermission = ref<Permission | null>(null)

// 获取权限列表
const fetchPermissionList = async () => {
  loading.value = true
  try {
    const params: PermissionQueryParams = {
      page: currentPage.value,
      num: pageSize.value
    }
    
    // 添加搜索条件
    if (filterForm.name) {
      params.name = filterForm.name
    }
    if (filterForm.type) {
      params.type = filterForm.type
    }
    if (filterForm.enable !== undefined) {
      params.enable = filterForm.enable
    }
    
    const res = await permissionApi.getAllPermissions(params)
    
    if (res && res.code === 200) {
      // 处理不同的响应结构
      if (res.data) {
        if (Array.isArray(res.data)) {
          permissionList.value = res.data
          totalCount.value = res.data.length
        } else if (res.data.data && Array.isArray(res.data.data)) {
          permissionList.value = res.data.data
          totalCount.value = res.data.totalCount || res.data.data.length
        } else if (res.data.totalCount !== undefined) {
          permissionList.value = res.data.data || []
          totalCount.value = res.data.totalCount
        } else {
          permissionList.value = []
          totalCount.value = 0
        }
      } else {
        permissionList.value = []
        totalCount.value = 0
      }
    } else {
      ElMessage.error(res?.message || '获取权限列表失败')
      permissionList.value = []
      totalCount.value = 0
    }
  } catch (error: any) {
    console.error('获取权限列表失败:', error)
    ElMessage.error(error.message || '获取权限列表失败')
    permissionList.value = []
    totalCount.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索输入防抖处理 - 使用网络搜索
const handleSearchInput = debounce(() => {
  currentPage.value = 1
  fetchPermissionList()
}, 500)

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchPermissionList()
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.name = ''
  filterForm.type = undefined
  filterForm.enable = undefined
  currentPage.value = 1
  fetchPermissionList()
}

// 页码改变
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchPermissionList()
}

// 每页条数改变
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchPermissionList()
}

// 新增权限
const handleAddPermission = () => {
  isEdit.value = false
  currentPermission.value = null
  dialogVisible.value = true
}

// 批量导入
const handleBatchAdd = () => {
  batchDialogVisible.value = true
}

// 编辑权限
const handleEdit = (permission: Permission) => {
  isEdit.value = true
  currentPermission.value = { ...permission }
  dialogVisible.value = true
}

// 删除权限
const handleDelete = (permission: Permission) => {
  if (permission.roles && permission.roles.length > 0) {
    ElMessage.warning('该权限已被角色使用，无法删除')
    return
  }

  ElMessageBox.confirm(
    `确定要删除权限 "${permission.name}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await permissionApi.deletePermission(permission.id)
      
      if (res && res.code === 200) {
        ElMessage.success('删除成功')
        fetchPermissionList()
      } else {
        ElMessage.error('删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 对话框成功回调
const handleDialogSuccess = () => {
  dialogVisible.value = false
  fetchPermissionList()
}

// 批量导入成功回调
const handleBatchSuccess = () => {
  batchDialogVisible.value = false
  fetchPermissionList()
}

// 获取类型标签类型
const getTypeTagType = (type: string): string => {
  const typeMap: Record<string, string> = {
    'MENU': 'primary',
    'BUTTON': 'success',
    'API': 'warning'
  }
  return typeMap[type] || 'info'
}

// 获取类型标签文本
const getTypeLabel = (type: string): string => {
  const option = PERMISSION_TYPE_OPTIONS.find(opt => opt.value === type)
  return option ? option.label : type
}

// 获取方法标签类型
const getMethodTagType = (method: string): string => {
  const methodMap: Record<string, string> = {
    'GET': 'success',
    'POST': 'primary',
    'PATCH': 'warning',
    'DELETE': 'danger'
  }
  return methodMap[method] || 'info'
}

// 加载数据
onMounted(() => {
  fetchPermissionList()
})
</script>

<style scoped>
.permission-list-tab {
  padding: 0;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
